﻿
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Newtonsoft.Json;
using System;
using System.Security.Claims;
using Yes.Application.User.Dto;
using Yes.Core.Context;
using Yes.Core.Extensions;
using Yes.Core.Helper;
using Yes.Domain;
using Yes.Domain.Context;
using Yes.Domain.Entity;


namespace Yes.Application.User
{
    public class UserService : BaseService, IUserService
    {
        private IRepository<UserEntity> _userRepository;


        public UserService(IRepository<UserEntity> userRepository)
        {
            _userRepository = userRepository;
        }

        public ResultDto Login(UserLoginDto dto)
        {
            if (_userRepository.Count() == 0)
            {
                _userRepository.Insert(new UserEntity() { UserName="admin", Email = "8720826@qq.com", Password = SecurityHelper.Md5("admin"), Url = "", NickName = "alt" });
            }


            UserEntity user = null;
            if (dto.UserName.Contains("@"))
            {
                user = _userRepository.Get(p => p.Email == dto.UserName);
            }
            else
            {
                user = _userRepository.Get(p => p.UserName == dto.UserName);
            }
            
            if (user == null)
            {
                return new ResultDto
                {
                    Status = false,
                    ErrorMessage = "用户不存在"
                };
            }
            if (user.Password!= SecurityHelper.Md5(dto.Password))
            {
                return new ResultDto
                {
                    Status = false,
                    ErrorMessage = "密码错误"
                };
            }

            var loginInfo = user.MapTo<LoginInfo>();
            loginInfo.LoginDate = DateTime.Now;

            //CookiesHelper.SetCookie("LoginInfo", SecurityHelper.DesEncrypt(JsonConvert.SerializeObject(loginInfo)));


            var identity = new Claim[] {
                new Claim(ClaimTypes.Name,user.Id.ToString())
            };


            YesHttpContext.Current.Request.HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(new ClaimsIdentity(identity, "LoginInfo")),
            new AuthenticationProperties()
            {
                ExpiresUtc = DateTime.UtcNow.Add(TimeSpan.FromDays(7)),
                IsPersistent = true
            });

            return new ResultDto
            {
                Status = true
            };
        }


        public ResultDto Logout()
        {
            //CookiesHelper.RemoveCookie("LoginInfo");

            YesHttpContext.Current.Request.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return new ResultDto
            {
                Status = true
            };
        }

        public LoginInfo GetLoginUser()
        {
            string name = YesHttpContext.Current.User.Identity.Name;
            int userId = 0;
            int.TryParse(name, out userId);



            //var html = SecurityHelper.DesDecrypt(CookiesHelper.GetCookieValue("LoginInfo"));
            //var loginInfo = JsonConvert.DeserializeObject<LoginInfo>(html);

          

            return _userRepository.Get(userId).MapTo<LoginInfo>();
        }

        public int GetLoginUserId()
        {
            var loginInfo = GetLoginUser();
            return loginInfo?.Id ?? 0;
        }

        public ResultDto ChangePasword(PasswordEditDto dto, LoginInfo loginInfo)
        {
            var result =   new ResultDto
            {
                Status = false
            };

            if (dto.NewPassword != dto.NewPassword2)
            {
                result.ErrorMessage = "两次新密码必须一致";
                return result;
            }

            if (dto.Password == dto.NewPassword)
            {
                result.ErrorMessage = "新密码不能和旧密码相同";
                return result;
            }

            var user = _userRepository.Get(loginInfo.Id);
            if (user.Password != SecurityHelper.Md5(dto.Password))
            {
                result.ErrorMessage = "请输入正确的密码";
                return result;
            }

            user.Password = SecurityHelper.Md5(dto.NewPassword);
            _userRepository.Update(user);

            return new ResultDto
            {
                Status = true
            };
        }


        public string Test(string val)
        {
            CookiesHelper.SetCookie("test", val);

            return CookiesHelper.GetCookieValue("test");
        }
    }
}
